#!/usr/bin/env bash
# shellcheck disable=SC2029
set -e

BIN="wow-update-ip"
TAG="latest"
IMAGE_NAME="${BIN}:${TAG}"
IMAGE_TAR_GZ="${BIN}.0.0.${BUILD_NUMBER}.tar.gz"

docker build -t "${IMAGE_NAME}" .
docker save "${IMAGE_NAME}" | gzip > "${IMAGE_TAR_GZ}"

scp "${IMAGE_TAR_GZ}" root@"${IP}":/root/

## ssh
echo "load image"

ssh root@"${IP}" "docker load --input /root/${IMAGE_TAR_GZ}"
ssh root@"${IP}" "gunzip -c ${IMAGE_TAR_GZ} | docker load"

echo "replace image"
ssh root@"${IP}"  "docker stop ${BIN} || true"
ssh root@"${IP}"  "docker rm ${BIN} || true"
ssh root@"${IP}"  "docker run -d --restart=always --net=host -v /var/log:/var/log --name ${BIN} ${IMAGE_NAME}"
ssh root@"${IP}"  "rm -rf /root/${IMAGE_TAR_GZ}"
#ssh root@"${IP}"  "docker image prune -f"

## clear local image
echo "clear local image"
docker rmi "${IMAGE_NAME}"